<template>
  <div>
    <v-row justify="start">
      <v-col
        cols="12"
        md="12"
      >
        <material-card
          color="primary"
          full-header
        >
          <template #title>
            <v-alert
              type="success"
              dense
              icon="mdi-arrow-left-right-bold"
            >
              {{ lanChar.status.THPStats }}
              <v-btn
                class="mx-0"
                fab
                icon
                x-small
                color="primary"
                @click="reflashStatus()"
              >
                <v-icon>mdi-cached</v-icon>
              </v-btn>
            </v-alert>
          </template>
          <v-row justify="start">
            <v-col
              cols="12"
              sm="9"
            >
              <v-sheet color="transparent">
                <div id="chart-g2-thp" />
              </v-sheet>
            </v-col>
            <v-col
              cols="12"
              sm="3"
            >
              <v-select
                v-model="groupName"
                dense
                outlined
                :items="groupItems"
                :label="lanChar.ruleConfig.MCGroupRuleName"
                class="mr-5"
                hide-details
              />
              <v-row
                dense
                align="center"
                class="mr-5"
              >
                <v-col
                  cols="12"
                  sm="3"
                >
                  <span>
                    {{ lanChar.statsPkts }}:
                  </span>
                </v-col>
                <v-col
                  cols="12"
                  sm="4"
                >
                  <v-icon class="pr-3">
                    mdi-alpha-r-box-outline
                  </v-icon>
                  <span>{{ groupThp.RxPkts }}</span>
                </v-col>
                <v-col
                  cols="12"
                  sm="4"
                >
                  <v-icon class="pr-3">
                    mdi-alpha-t-box-outline
                  </v-icon>
                  <span>{{ groupThp.TxPkts }}</span>
                </v-col>
              </v-row>
              <v-divider class="mr-5" />
              <v-row
                dense
                align="center"
                class="mr-5"
              >
                <v-col
                  cols="12"
                  sm="3"
                >
                  <span>
                    {{ lanChar.statsBytes }}:
                  </span>
                </v-col>
                <v-col
                  cols="12"
                  sm="4"
                >
                  <v-icon class="pr-3">
                    mdi-alpha-r-box-outline
                  </v-icon>
                  <span>{{ groupThp.RxBytes }}</span>
                </v-col>
                <v-col
                  cols="12"
                  sm="4"
                >
                  <v-icon class="pr-3">
                    mdi-alpha-t-box-outline
                  </v-icon>
                  <span>{{ groupThp.TxBytes }}</span>
                </v-col>
              </v-row>
              <v-divider class="mr-5" />
              <v-row
                dense
                align="center"
                class="mr-5"
              >
                <v-col
                  cols="12"
                  sm="3"
                >
                  <span>
                    {{ lanChar.thpBitrate }}:
                  </span>
                </v-col>
                <v-col
                  cols="12"
                  sm="9"
                >
                  <v-row dense>
                    <v-icon class="pr-3">
                      mdi-alpha-r-box-outline
                    </v-icon>
                    <span>{{ rxBitrate }}</span>
                  </v-row>
                  <v-row dense>
                    <v-icon class="pr-3">
                      mdi-alpha-t-box-outline
                    </v-icon>
                    <span>{{ txBitrate }}</span>
                  </v-row>
                </v-col>
              </v-row>
              <v-divider class="mr-5" />
              <v-row
                dense
                align="center"
                class="mr-5"
              >
                <v-col
                  cols="12"
                  sm="3"
                >
                  <span>
                    {{ lanChar.thpPktsPS }}:
                  </span>
                </v-col>
                <v-col
                  cols="12"
                  sm="9"
                >
                  <v-row dense>
                    <v-icon class="pr-3">
                      mdi-alpha-r-box-outline
                    </v-icon>
                    <span>{{ rxPktrate }}</span>
                  </v-row>
                  <v-row dense>
                    <v-icon class="pr-3">
                      mdi-alpha-t-box-outline
                    </v-icon>
                    <span>{{ txPktrate }}</span>
                  </v-row>
                </v-col>
              </v-row>
              <v-divider class="mr-5" />
              <div />
            </v-col>
          </v-row>
        </material-card>
      </v-col>
    </v-row>
    <material-snackbar-tip
      v-model="snackbarDescp.snackbar"
      :type="snackbarDescp.snackbarType"
      :timeout="snackbarDescp.snackbarTimeout"
      v-bind="{
        bottom: true,
        right: true
      }"
      :text="snackbarDescp.snackbarContent"
    />
    <alert-dialog
      v-model="alert.dialog"
      :title="alert.title"
      :msg="alert.msg"
    />
  </div>
</template>

<script>
  import globalDef from '@/util/globals'
  import { Chart } from '@antv/g2'
  import * as mcAxios from '@/util/mcaxios'
  import lan from '@/util/lan-char'
  export default {
    name: 'ThroughputInfo',
    data: () => ({
      checking: false,
      heartbeats: [],
      deviceAddr: undefined,
      lanChar: lan.GetLan(),
      statusTimer: 0,
      chartTimer: 0,
      groupName: '',
      groupItems: [
        'GROUP-1',
        'GROUP-2',
        'GROUP-3',
      ],
      groupThp: {
        RxPkts: 0,
        TxPkts: 0,
        RxBytes: 0,
        TxBytes: 0,
      },
      groupThps: [],
      chartData: [
        { time: '', thp: 0, direction: 'rx' },
        { time: '', thp: 0, direction: 'tx' },
      ],
      chartG2THP: {},
      lastTime: 0,
      lastRxBytes: 0,
      lastTxBytes: 0,
      lastRxPkts: 0,
      lastTxPkts: 0,
      // snackbar data
      snackbarDescp: {
        snackbar: false,
        snackbarContent: 'snackbar content',
        snackbarTimeout: 2000,
        snackbarType: 'info',
      },
      // dialog data
      alert: {
        dialog: false,
        title: '',
        msg: '',
      },
    }),
    computed: {
      rxBitrate: function () {
        var rxThp = this.chartData[this.chartData.length - 2].thp
        return this.formatThp(rxThp) + 'bps'
      },
      txBitrate: function () {
        var txThp = this.chartData[this.chartData.length - 1].thp
        return this.formatThp(txThp) + 'bps'
      },
      rxPktrate: function () {
        var rxPktsRate = this.chartData[this.chartData.length - 2].pktsRate
        return this.formatThp(rxPktsRate) + 'pps'
      },
      txPktrate: function () {
        var txPktsRate = this.chartData[this.chartData.length - 1].pktsRate
        return this.formatThp(txPktsRate) + 'pps'
      },
    },
    watch: {
      groupName: {
        handler (newValue, oldValue) {
          this.mcGroupThpInfosStart()
        },
        deep: false,
      },
      groupThps: {
        handler (newValue, oldValue) {
          this.initCharData()
          this.chartG2ThpUpdate()
        },
        deep: false,
      },
    },
    created () {
      globalDef.VueObject.$on('lanChange', lanChar => {
        this.lanChar = lanChar
      })

      this.getMcGroupsInfo()
      this.reflashStatus()
      this.startReflash()
    },
    mounted () {
      this.chartThpG2Init()
    },
    beforeDestroy () {
      clearInterval(this.statusTimer)
      clearInterval(this.chartTimer)
    },
    methods: {
      tipInfo (level, content, timeout) {
        this.snackbarDescp.snackbarType = level
        this.snackbarDescp.snackbarContent = content
        this.snackbarDescp.snackbarTimeout = timeout
        this.snackbarDescp.snackbar = true
      },
      alertInfo (title, content) {
        this.alert.dialog = true
        this.alert.title = title
        this.alert.msg = content
      },
      formatThp (v) {
        if (v > 1000000000) {
          return String(Math.ceil(v / 1000000000)) + 'G'
        } else if (v > 1000000) {
          return String(Math.ceil(v / 1000000)) + 'M'
        } else if (v > 1000) {
          return String(Math.ceil(v / 1000)) + 'K'
        } else {
          return String(v)
        }
      },
      chartThpG2Init () {
        this.chartG2THP = new Chart({
          container: 'chart-g2-thp',
          autoFit: true,
          height: 300,
        })
        var chart = this.chartG2THP
        var data = this.chartData
        chart.data(data)
        chart.scale('thp', {
          nice: true,
        })
        chart.scale('thp', {
          alias: this.lanChar.status.THPStats,
        })
        chart.axis('thp', {
          title: {},
        })
        chart.tooltip({
          showMarkers: true,
        })
        chart.interaction('active-region')
        chart.line().position('time*thp').color('direction')
        chart.render()
      },
      chartG2ThpUpdate () {
        this.chartG2THP.render()
      },
      reflashStatus () {
        this.getMcGroupsInfo()
        this.updateCharData()
      },
      reflashChart () {
        this.chartG2ThpUpdate()
      },
      startReflash () {
        clearInterval(this.statusTimer)
        this.statusTimer = setInterval(this.reflashStatus, globalDef.STATUS_QUERY_INTERVAL)
        clearInterval(this.chartTimer)
        this.chartTimer = setInterval(this.reflashChart, globalDef.STATUS_CHART_REFLASH_INTERVAL)
      },
      getMcGroupsInfo () {
        const data = {
          request_type: 'mc groups info get',
          instance_id: 'instance_id',
          sequence_no: 1000,
        }
        mcAxios.axiosGetConfig(data)
          .then((res) => {
            if (res.data.status === true) {
              this.groupItems = []
              res.data.data.forEach((e, i) => {
                this.groupItems[i] = e.GroupName
              })
              if (this.groupName === '' && this.groupItems.length !== 0) {
                this.groupName = this.groupItems[0]
              }
            } else {
              console.log('getMcGroupsInfo get res fail')
            }
          })
          .catch((e) => {
            console.log('getMcGroupsInfo get fail: ', e)
          })
      },
      mcGroupThpInfosStart () {
        const data = {
          request_type: 'mc group thp info start',
          instance_id: 'instance_id',
          sequence_no: 1000,
          data: {
            GroupName: this.groupName,
          },
        }
        mcAxios.axiosGetTrafficLoad(data)
          .then((res) => {
            if (res.data.status === true) {
              const data = {
                request_type: 'mc group thp infos get',
                instance_id: 'instance_id',
                sequence_no: 1000,
                data: {
                  GroupName: this.groupName,
                },
              }
              mcAxios.axiosGetTrafficLoad(data)
                .then((res) => {
                  if (res.data.status === true) {
                    this.groupThps = res.data.data
                  } else {
                    console.log('mcGroupThpInfosStart get res fail')
                  }
                })
                .catch((e) => {
                  console.log('mcGroupThpInfosStart get fail: ', e)
                })
            } else {
              this.tipInfo('info', this.lanChar.tipInfoOperateRespFail + res.data.msg, globalDef.TIPINFO_DISPLAY_DURATION)
            }
          })
          .catch((e) => {
            console.log('setMcGroupThpStart set fail: ', e)
          })
      },
      async getLatestMcGroupThpInfo () {
        const data = {
          request_type: 'latest mc group thp info get',
          instance_id: 'instance_id',
          sequence_no: 1000,
          data: {
            GroupName: this.groupName,
          },
        }
        return mcAxios.axiosGetTrafficLoad(data)
      },
      initCharData () {
        this.lastRxBytes = 0
        this.lastTxBytes = 0
        this.lastRxPkts = 0
        this.lastTxPkts = 0
        this.lastTime = 0
        this.chartData.splice(0, this.chartData.length)
        this.groupThps.forEach((e, i) => {
          this.chartData[2 * i] = {
            time: new Date(e.Time).toLocaleTimeString(),
            thp: ((e.RxBytes - this.lastRxBytes) * 8 * 1000) / (e.Time - this.lastTime),
            pktsRate: ((e.RxPkts - this.lastRxPkts) * 1000) / (e.Time - this.lastTime),
            direction: 'rx',
          }
          this.chartData[2 * i + 1] = {
            time: new Date(e.Time).toLocaleTimeString(),
            thp: ((e.TxBytes - this.lastTxBytes) * 8 * 1000) / (e.Time - this.lastTime),
            pktsRate: ((e.TxPkts - this.lastTxPkts) * 1000) / (e.Time - this.lastTime),
            direction: 'tx',
          }
          this.lastRxBytes = e.RxBytes
          this.lastTxBytes = e.TxBytes
          this.lastRxPkts = e.RxPkts
          this.lastTxPkts = e.TxPkts
          this.lastTime = e.Time
        })
      },
      async updateCharData () {
        const res = await this.getLatestMcGroupThpInfo()
        try {
          if (res.data.status === true) {
            this.groupThp = res.data.data
          } else {
            console.log('getLatestMcGroupThpInfo get res fail')
          }
        } catch (e) {
          console.log('getLatestMcGroupThpInfo get fail: ', e)
        }

        var v = this.groupThp
        if (this.chartData.length > 2 * 50) {
          this.chartData.shift()
        }
        this.chartData.push({
          time: new Date(v.Time).toLocaleTimeString(),
          thp: ((v.RxBytes - this.lastRxBytes) * 8 * 1000) / (v.Time - this.lastTime),
          pktsRate: ((v.RxPkts - this.lastRxPkts) * 1000) / (v.Time - this.lastTime),
          direction: 'rx',
        })
        this.chartData.push({
          time: new Date(v.Time).toLocaleTimeString(),
          thp: ((v.TxBytes - this.lastTxBytes) * 8 * 1000) / (v.Time - this.lastTime),
          pktsRate: ((v.TxPkts - this.lastTxPkts) * 1000) / (v.Time - this.lastTime),
          direction: 'tx',
        })
        this.lastRxBytes = v.RxBytes
        this.lastTxBytes = v.TxBytes
        this.lastRxPkts = v.RxPkts
        this.lastTxPkts = v.TxPkts
        this.lastTime = v.Time
      },
    },
  }

</script>
